package cn.xd.security.exception;

import cn.hutool.http.ContentType;
import cn.xd.common.enums.common.ResultCodeEnum;
import cn.xd.common.exception.BizException;
import cn.xd.common.response.ResponseResult;
import cn.xd.security.constants.SecurityConstant;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.codec.CharEncoding;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author : mirzaLin
 * @date : 2024/1/29
 * @description :
 **/
@Component
public class MainAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException
            accessDeniedException) throws BizException, IOException {
        response.setCharacterEncoding(CharEncoding.UTF_8);
        response.setContentType(ContentType.JSON.getValue());
        response.getWriter()
                .write(JSON.toJSONString(ResponseResult.failed(SecurityConstant.PERMISSION_DENIED, ResultCodeEnum.BIZ_ERROR)));
    }
}
